package com.example.qt.ptplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.qt.ptplatform.entity.FavoriteTorrent;
import com.example.qt.ptplatform.mapper.FavoriteTorrentMapper;
import com.example.qt.ptplatform.service.FavoriteTorrentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 种子收藏服务实现类
 */
@Service
public class FavoriteTorrentServiceImpl implements FavoriteTorrentService {

    @Autowired
    private FavoriteTorrentMapper favoriteTorrentMapper;

    @Override
    @Transactional
    public boolean save(FavoriteTorrent favorite) {
        if (favorite == null || favorite.getUserId() == null || favorite.getTorrentId() == null) {
            return false;
        }
        return favoriteTorrentMapper.insert(favorite) > 0;
    }

    @Override
    @Transactional
    public boolean remove(LambdaQueryWrapper<FavoriteTorrent> wrapper) {
        return favoriteTorrentMapper.delete(wrapper) > 0;
    }

    @Override
    public long count(LambdaQueryWrapper<FavoriteTorrent> wrapper) {
        return favoriteTorrentMapper.selectCount(wrapper);
    }

    @Override
    public boolean isFavorite(Integer userId, Integer torrentId) {
        if (userId == null || torrentId == null) {
            return false;
        }

        LambdaQueryWrapper<FavoriteTorrent> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(FavoriteTorrent::getUserId, userId)
                .eq(FavoriteTorrent::getTorrentId, torrentId)
                .last("LIMIT 1");

        Integer count = favoriteTorrentMapper.selectCount(wrapper);
        return count != null && count > 0;
    }

    @Override
    public List<Integer> getUserFavoriteTorrentIds(Integer userId) {
        if (userId == null) {
            return Collections.emptyList();
        }

        LambdaQueryWrapper<FavoriteTorrent> wrapper = Wrappers.lambdaQuery();
        wrapper.select(FavoriteTorrent::getTorrentId)
                .eq(FavoriteTorrent::getUserId, userId)
                .orderByDesc(FavoriteTorrent::getCreateTime);

        return favoriteTorrentMapper.selectList(wrapper)
                .stream()
                .map(FavoriteTorrent::getTorrentId)
                .collect(Collectors.toList());
    }
}